package com.example.demo.netty;

import com.google.common.base.Throwables;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

/**
 * @description: netty 接入demo
 * @author: panyundong
 * @date: 2020/6/8
 **/
@Service
@Log4j2
public class NettyServer {

    private final Integer PORT = 8090;

    public void bootstrap() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new MattressSocketServerInitialzer())
                    .childOption(ChannelOption.TCP_NODELAY, true);
            b.bind(PORT).sync().channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("start up netty server exception {}", Throwables.getStackTraceAsString(e));
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
